{% extends 'common/base.html' %}
{% block css %}
    <link rel="stylesheet"
          href="{{ url_for('static',filename='css/plugins/froalaEditer/froala_editor.pkgd.min.css') }}"/>
    <link rel="stylesheet" href="{{ url_for('static',filename='css/plugins/froalaEditer/froala_style.min.css') }}"/>
    <link rel="stylesheet" href="{{ url_for('static',filename='css/question_import.css') }}"/>
    <style>
        #qtExample, #qtStandard {
            border: 2px solid #b5d6fd;
            max-height: 230px;
            overflow: auto;
        }

        #edit .fr-toolbar, .second-toolbar {
            display: none;
        }

        #edit, .box {
            height: 400px;
        }
         .demo{
             font-size: 14px;
             margin-left: 0;
             margin-bottom: 10px;
             font-weight: 500;
             -webkit-user-select: none;
             -moz-user-select: none;
         }
    .input-example-question{
        margin: 10px;
    }
    </style>
{% endblock %}
{% block content %}
    <section class="content-header">
        <div>
            <ol class="breadcrumb">
                <li><a href="#"><i class="fa fa-dashboard"></i> 题库管理</a></li>
                <li class="active">添加试题</li>
            </ol>
        </div>
    </section>
    <section class="content" id="showcontent">
        <div class="row">
            <div class="col-md-12">
                <div class="box box-primary">
                    <div class="box-header with-border">
                        <h3 class="box-title">添加试题</h3>
                    </div>
                    <form method="post" action="" id="qtForm">
                        <div class="batch-cont" id="inputArea">
                            <div class="batch-input clearfix">
                                <div class="batch-input-box">
                                    <div class="toolbar">
                                        <span class="title">输入区：</span>
                                        <div class="toolbar-right" style="margin: 0 15px">
                                        <span class="example" id="showExample" data-toggle="collapse"
                                              data-target="#qtExample">输入范例<i class="fa fa-chevron-up"></i></span>
                                            </span>
                                            <span class="standard" id="showStandard" data-toggle="collapse"
                                                  data-target="#qtStandard">输入规范<i class="fa fa-chevron-up"></i></span>
                                        </div>
                                    </div>
                                    <div id="qtExample" class="collapse">
                                        <div class="input-example">
                                            <div class="input-example-content">
                                                <div class="input-example-question">
                                                    <p style="color: #1A8CFE;" class="demo">
                                                        单选题</p>
                                                    <p class="input-com-detail" style="margin-left: 10px;">
                                                        <span>1.驾驶人有下列哪种违法行为一次记6分</span><br>
                                                        <span>A、使用其他车辆行驶证</span><br>
                                                        <span>B、饮酒后驾驶机动车</span><br>
                                                        <span>C、车速超过规定时速50%以上</span><br>
                                                        <span>D、违法占用应急车道行驶</span><br>
                                                        <span>答案:D </span><br>
                                                        <span>解析:请仔细阅读交规<span class="txt-red">(若无解析本行可不填)</span></span><br>
                                                        <span>难度:简单<span class="txt-red">(可不填)</span></span><br>
                                                    </p>
                                                </div>
                                                <div class="input-example-question">
                                                    <p style="color:#4fc08d " class="demo">多选题</p>
                                                    <p class="input-com-detail" style="margin-left: 10px;">
                                                        <span>1.驾驶人有下列哪种违法行为一次记6分？</span><br>
                                                        <span>A、使用其他车辆行驶证</span><br>
                                                        <span>B、饮酒后驾驶机动车</span><br>
                                                        <span>C、车速超过规定时速50%以上</span><br>
                                                        <span>D、违法占用应急车道行驶</span><br>
                                                        <span>答案:ABCD</span><br>
                                                        <span>解析:请仔细阅读交规 <span >(若无解析本行可不填)</span></span>
                                                        <br style="visibility: hidden;">
                                                        <span>难度:普通<span class="txt-red">(可不填)</span></span><br>
                                                    </p>
                                                </div>
                                                <div class="input-example-question">
                                                    <p style="color:#F76377 " class="demo">判断题</p>
                                                    <p class="input-com-detail" style="margin-left: 10px;">
                                                        <span>1.国际象棋起源于英国吗？</span><br>
                                                        <span>答案:对</span><br>
                                                        <span>解析:无 <span>(若无解析本行可不填)</span></span>
                                                        <br style="visibility: hidden;">
                                                        <span>难度:困难<span class="txt-red">(可不填)</span></span><br>
                                                    </p>
                                                </div>
                                                <div class="input-example-question">
                                                    <p style="color:#A06AD2" class="demo">填空题</p>
                                                    <p class="input-com-detail" style="margin-left: 10px;">
                                                        <span>1.我国古典四大名著是（）（）（）（）</span><br>
                                                        <span>答案:红楼梦&amp;&amp;石头记|水浒传|三国演义|西游记 </span><br>
                                                        <span>解析:无 <span>(若无解析本行可不填)</span></span>
                                                        <br style="visibility: hidden;">
                                                        <span>难度:简单<span class="txt-red">(可不填)</span></span><br>
                                                    </p>
                                                </div>
                                                <div class="input-example-question">
                                                    <p style="color:#C9A310" class="demo">简答题</p>
                                                    <p class="input-com-detail" style="margin-left: 10px;">
                                                        <span>1.请论述全球化对国家政治产生了哪些深刻的影响？</span><br>
                                                        <span>答案:全球化使国家主权受到一定的制约；全球化对政府的治理提出了更高的要求。</span><br
                                                            style="visibility: hidden;">
                                                        <span>解析:无  <span>(若无解析本行可不填)</span></span>
                                                        <br style="visibility: hidden;">
                                                        <span>难度:普通 <span class="txt-red">(可不填)</span></span><br>
                                                    </p>
                                                </div>
                                            </div>
                                        </div>
                                    </div>

                                    <div id="qtStandard" class="collapse">
                                        <div class="input-rule">
                                            <div class="input-rule-content">
                                                <p class="input-common-title"
                                                   style="margin-left: -10px;color: #1A8CFE;margin-bottom: 10px;font-weight: 500">
                                                    输入规范</p>
                                                1、所有题型标号支持1.或1、或（1）三种格式。<br>
                                                2、所有题型必须含有 “ <span style="color: #F76377">答案：</span>”字段，且不能为空。<br>
                                                3、所有题型 “ <span style="color: #F76377">解析：</span>” 字段非必需，没有可不填。<br>
                                                4、所有题型“ <span style="color: #F76377">难度：</span>”字段非必需，没有可不填。<br>
                                                5、所有题型 “ <span style="color: #F76377">试题标签：</span>”
                                                6、<span style="color: #1A8CFE">选择题</span>最少支持2个选项A,B，最多支持4个选项A,B,C,DH且按照顺序使用。<br>
                                                7、<span style="color: #1A8CFE">选择题</span>A-D这些选项号与内容之间要用、或 . 分开。<br>
                                                8、<span style="color: #1A8CFE">选择题</span>答案中请勿加分隔符或者空格。<br>
                                                9、<span style="color: #F76377">判断题</span>答案支持 “错误”，“正确” 或者 “错”，“对”。<br>
                                                10、<span style="color:#A06AD2">填空题</span>仅支持题目中出现括号。<br>
                                                11、<span style="color:#A06AD2">填空题</span>目里的多个填空答案要用 | 分割，单个答案不用添加。<br>
                                                12、<span style="color:#A06AD2">填空题</span>的填空答案支持输入同义词，用&amp;&amp;连接多个同义词答案。<br>
                                                13、<span style="color:#C9A310">简答题</span>可以包含 “普通关键词：” 和 “
                                                核心关键词：”，没有可不填。<br>
                                                14、<span style="color:#C9A310">简答题</span>多个关键词用、去分隔，并列关键词（或的关系）用 |
                                                去分隔。<br>
                                            </div>
                                        </div>
                                    </div>

                                    <div class="textarea-group">
                                        <div id="edit"></div>
                                    </div>
                                </div>
                                <div class="batch-preview-box">
                                    <div class="toolbar">
                                        <span class="title">检查区：</span>
                                        <span class="error-text" id="errorText"><span class="count"
                                                                                      id="errorCount"></span>处错误，请参照例题修改</span>
                                        <button class="btn btn-s-blue" id="nextError">下一处</button>
                                    </div>
                                    <div class="box" style=" height: 400px;overflow: auto;">
                                        <div id="preview">
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="box-footer" style="text-align: center">
                            <button id="importBtn" class="btn btn-primary">录入</button>
                            <a href="{{ url_for("main.question_add_html",type=0) }}" class="float-right btn">返回</a>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </section>
{% endblock %}
{% block js %}
    <script src="{{ url_for('static',filename='js/plugins/froalaEditer/froala_editor.pkgd.min.js') }}"></script>
    <script src="{{ url_for('static',filename='js/plugins/froalaEditer/zh_cn.js') }}"></script>
    <script src="{{ url_for('static',filename='js/plugins/auto-line-number-batch.js') }}"></script>
    <script src="{{ url_for('static',filename='js/plugins/markdown-v1.1.js') }}"></script>
    <script src="{{ url_for('static',filename='js/plugins/layer/layer.js') }}"></script>

    <script>
        $(function () {
            $('#qtExample').on('show.bs.collapse', function () {
                $('#qtStandard').collapse('hide')
            })

            $('#qtStandard').on('show.bs.collapse', function () {
                $('#qtExample').collapse('hide')
            })

            initFroalaEditor();
        });
        var qt_type = "1";
        var typeName = ['单选题', '多选题', '判断题', '填空题', '简答题'];
        var nameReg = /^\n?\s*(([0-9]+\s*[.|、])|(((\()|（)[0-9]+((\))|）)))\s*(.*?)\s*(?:\n|$)/g;
        var singleReg = /^\n?\s*(答案[:：])\s*(.*?)\s*(?:\n|$)/g;
        var fillReg = /([\(|\（]\s*[\)|\）])/g;

        function initFroalaEditor() {
            new FroalaEditor('#edit', {
                placeholderText: '请将所选试题复制到这里',
                charCounterCount: false,
                language: 'zh_cn',
                heightMax: 600,
                spellcheck: false,
                pastePlain: true,
                toolbarInline: false,
                pasteAllowLocalImages: true,
                imageDefaultWidth: 'auto',//图片默认宽度
                imageDefaultAlign: 'left',
                wordAllowedStyleProps: [],//允许从word粘贴的标签的样式
                htmlAllowedTags: ["p", "img", "br", "sub", "sup", "div"],//允许出现的标签
                imageAllowedTypes: ["jpeg", "jpg", "png"],
                imageUploadParam: "multipartFile",
                imageUploadParams: {code: 1},
                imageUploadURL: '',
                pasteDeniedAttrs: ['class', 'id', 'style'],
                quickInsertEnabled: false,
                events: {
                    'contentChanged': function () {
                        const editor = this;
                        setTimeout(function () {
                            $('#preview').html("");
                            var newArr = [];
                            var indexArr = [];
                            var questionArr = [];
                            var detail = [];
                            var contentText = editor.html.get().replace(/<p>/g, "\n\n").replace(/<\/p>/g, "\n\n").replace(/<br>/g, "\n\n").replace(/auto;">/g, 'auto;">\n\n').split('\n');
                            //去除空格
                            contentText.forEach(function (value) {
                                if (value) {

                                    value = value.replace(/&nbsp;/g, ' ');
                                    value = '&nbsp;&nbsp;&nbsp;' + value;
                                    value = value.replace(/&nbsp;/g, "\n");
                                    newArr.push(value)
                                }
                            });
                            //寻找相应的下标
                            newArr.forEach(function (value, index) {
                                if (value.match(nameReg)) {
                                    indexArr.push(index)
                                }
                            });
                            //截取完整小题
                            indexArr.forEach(function (value, index) {
                                questionArr.push(newArr.slice(indexArr[index], indexArr[index + 1]))
                            });

                            $('.batch-preview-box .toolbar .title').text(questionArr.length > 0 ? '检查区(共' + questionArr.length + '题)：' : '检查区：');

                            //判断题型，赋值qt_type
                            questionArr.forEach(function (value) {
                                var allValue = value.join(' ');
                                //匹配没有答案的情况(  答案：/【答案】)
                                if (!allValue.match(/\n+\s*【\s*答案\s*】\s*/g) && !allValue.match(/\n+\s*(答案[:：])\s*/g)) {
                                    //匹配到选项存在则默认为单选题先判断是否带有a.类似标志
                                    if (allValue.match(/\n+\s*[a-h]\s*[.|、]/ig)) {

                                        getClassify(value, detail, 1)

                                    } else if (fillReg.test(allValue)) {
                                        //在判断是否带有（）
                                        getClassify(value, detail, 4)
                                    } else {
                                        //否则默认为简答题
                                        getClassify(value, detail, 5)
                                    }

                                } else {
                                    var answerReg = /^\s*\n?【\s*答案\s*】\s*/;
                                    var answerJude = /\n\n\n\s*【\s*答案\s*】|\n\n\n\s*答案[:：]/g;
                                    //针对存在多个答案的情况
                                    if (allValue.match(answerJude).length > 1) {
                                        value.forEach(function (ele, i) {
                                            if (ele.match(answerJude)) {
                                                value = value.slice(0, i + 1)
                                            }

                                        })
                                    }
                                    value.forEach(function (val) {
                                        // 处理下中文括号
                                        if (answerReg.test(val)) {
                                            val = val.replace(answerReg, '答案：');
                                        }
                                        //只有答案两个字的情况
                                        if (/^\s*\n?答案\s*\n?$/.test(val)) {
                                            val = val.replace(/^\s*\n?(答案)\s*/, '答案：');
                                        }
                                        if (val.match(singleReg)) {
                                            var m = val.match(singleReg);//匹配答案项
                                            var isAnswer = m[0].replace(/^\n?\s*(答案[:|：])\s*/, "");//寻找答案后的字符串
                                            //有答案字段，没有正确的答案
                                            if (!isAnswer) {
                                                var newString = value.join(' ');
                                                if (newString.match(/\n?\s*[a-h][.|、]\s*/ig)) {
                                                    //有选项情况下，默认为单选题
                                                    getClassify(value, detail, 1)
                                                } else {
                                                    //填空题筛选
                                                    if ((newString.split('答案')[0]).match(fillReg)) {
                                                        getClassify(value, detail, 4);
                                                        return false
                                                    }
                                                    //无选项情况下，默认为简答题（主要包括判断题与简答题的区分）
                                                    getClassify(value, detail, 5)
                                                }
                                            } else {
                                                //word版多选题带,号处理
                                                if (isAnswer.match(/^([a-h][,|，]){0,7}([a-h])$/ig)) {
                                                    isAnswer = isAnswer.replace(/,|，/g, '')
                                                }
                                                var isSelect = isAnswer.match(/^\s*[a-h]{1,8}\s*(?:\n|$)/i);//单选/多选
                                                var isJude = isAnswer.match(/^\s*(正确|错误|对|错)\s*(?:\n|$)/i);//判断
                                                var isSelects = [] //该数组用于接收处理玩空字符串之后的isSelect
                                                // 针对大小写选项重复
                                                if (isSelect) {
                                                    //  数组去重
                                                    isSelect = (isSelect[0].split('')).filter(function (ele, i, array) {
                                                        return array.indexOf(ele) === i;
                                                    });
                                                    //二次处理isSelect,去除空字符串
                                                    isSelect.forEach(function (value1) {
                                                        if ($.trim(value1)) {
                                                            isSelects.push(value1)
                                                        }
                                                    });
                                                    //排序
                                                    isSelects.sort();
                                                    //1，2项比较是否为同一个选项(a,A)
                                                    if (isSelects.length === 2 && isSelects[0].toLocaleLowerCase() === isSelects[1]) {
                                                        isSelects = isSelects.splice(0, 1)
                                                    }
                                                }
                                                //单选题
                                                if (isSelects && isSelects.length === 1) {
                                                    getClassify(value, detail, 1)
                                                }
                                                //多选题
                                                if (isSelects && isSelects.length > 1) {
                                                    getClassify(value, detail, 2)
                                                }
                                                //判断题
                                                if (isJude) {
                                                    getClassify(value, detail, 3)
                                                }
                                                if (!isSelect && !isJude) {
                                                    // 填空题
                                                    if ((((value.join(" ").split('答案:'))[0].match(fillReg)) && (value.join(" ").split('答案:')).length > 1)
                                                        ||
                                                        (((value.join(" ").split('答案：'))[0].match(fillReg))) && (value.join(" ").split('答案：')).length > 1) {
                                                        getClassify(value, detail, 4)
                                                    } else {
                                                        //简答题
                                                        getClassify(value, detail, 5)
                                                    }
                                                }
                                            }
                                        }
                                    })
                                }
                            });

                            var html = '';
                            //没有数据时隐藏检查处错误提示
                            if (detail.length === 0) {
                                $("#errorCount").text('');
                                $("#errorText").hide();
                                $("#nextError").hide()
                            }
                            var ii = -1;//计数
                            detail.forEach(function (value) {
                                ii++;
                                qt_type = value.type;
                                html = markdown.toHTML((value.name).join(''));
                                $('div#preview').append(html);
                                // 标记答案
                                markAnswer(qt_type, ii);
                                changeSize(ii);
                                //  错误点及时检测
                                var errorNum = $('.check_error').length;
                                if (errorNum > 0) {
                                    $("#errorCount").text(errorNum);
                                    $("#errorText").show();
                                    if (errorNum === 1) {
                                        $("#nextError").text('查看').show();
                                    } else {
                                        $("#nextError").text('下一处').show();
                                    }
                                } else {
                                    $("#errorCount").text('');
                                    $("#errorText").hide();
                                    $("#nextError").hide()
                                }
                            });

                            //禁止右侧多选点击，禁止默认事件
                            $(".key input").click(function () {
                                return false
                            })
                            $(".body-content .cont-r .tab-content .batch-type .simulationOption div.now_diff").click(); //纠正难度错误
                        }, 1500)
                    }
                }
            })
        }

        // 标记答案
        function markAnswer(type, ii) {
            var list = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'];
            $(".question").eq(ii).each(function (index, element) {
                var $that = $(this);
                var titleNum = $(this).find('.type-box .title').text();
                var answerText = $(this).find(".qt_answer").text().replace(/^\s*答案\s*[:：]/, "");
                //word版多选题带,号处理
                if (answerText.match(/^([a-h][,|，]){0,7}([a-h])$/ig)) {
                    answerText = answerText.replace(/,|，/g, '')
                }
                var answer = answerText.toUpperCase();
                //处理下只有图片的情况
                var checkTitle = $(this).find('.qt_title').text().replace($(this).find('.type-box').text(), '')
                if ($.trim(checkTitle) === '') {
                    if ($(this).find('.qt_title img').length < 1) {
                        $(this).find('.qt_title').addClass('qt_error').html('题目（至少两个字)')
                    }
                }
                //检测是否按顺序排序
                var select = $(this).find('.key .title').text();
                var type = $(this).data('type');
                select = select.split('.').join("");

                //处理题目中的题号带括号，替换下中文括号
                titleNum = titleNum.replace(/（/, '(');
                titleNum = titleNum.replace(/）/, ')');
                $(this).find('.type-box .title').text(titleNum);

                //错误标记check_error
                if ($(this).find('.error,.qt_error').length > 0) {
                    $(this).addClass("check_error")
                }
                if (type == "1" || type == "2") {
                    for (var k = 0, selectLen = select.length; k < selectLen; k++) {
                        //根据选项与ACSII的比较，判断是否为正常的排序及重复选项的存在
                        if (!(select[k] === String.fromCharCode(65 + k))) {
                            $(this).addClass("check_error");
                            $(this).find('.key').addClass('qt_error')
                        }
                    }
                    for (var i = 0, listLen = list.length; i < listLen; i++) {
                        //标记选项框
                        if (answer.search(list[i]) !== -1) {
                            $(this).find(".key_" + list[i] + " .checkOrRadio").prop("checked", true);
                        } else {
                            $(this).find(".key_" + list[i] + " .checkOrRadio").attr("disabled", true);

                        }
                    }
                    //根据选项最后一位的ASCII码 与选项对比小于即为不存选项（大写比较）
                    //单选题判断答案是否存在
                    // 过滤空字符串
                    var answerhandle = answer.split('').filter(function (msg) {
                        return msg && msg.trim()

                    });
                    //单选题判断答案是否存在
                    if (answerhandle.length === 1) {
                        if (select.slice(-1).charCodeAt() < answerhandle[0].toLocaleUpperCase().charCodeAt()) {
                            $that.addClass("check_error");
                            $that.find(".qt_answer").removeAttr('hidden').addClass('qt_error').text('答案不存在！')
                        }
                    }

                    // 多选题判断答案是否存在
                    if (answerhandle.length > 1) {

                        for (var j = 0, answerLen = answerhandle.length; j < answerLen; j++) {
                            if (answerhandle[j].charCodeAt() > select.slice(-1).charCodeAt()) {
                                $that.addClass("check_error");
                                $that.find(".qt_answer").removeAttr('hidden').addClass('qt_error').text('答案不存在！')
                            }
                        }
                    }
                    //题目有错误时把单多选按钮隐藏
                    if ($(this).find(".qt_error").length != 0) {
                        $(this).find('.change-type').hide()
                    } else {
                        $(this).find('.change-type').show()
                    }
                }
                if (type == '4') {
                    //  填空题括号与答案对应，先进行空元素匹配，在进行重复答案匹配
                    var fillReg = /([\(|\（]\s*[\)|\）])/g;
                    var newAnswer = [];
                    if ($(this).find('.qt_title').text().match(fillReg)) {
                        var fillNum = $(this).find('.qt_title').text().match(fillReg).length;
                    }
                    var answerNum = answerText.split('|');
                    // 先判断长度是否相等
                    if (fillNum !== answerNum.length) {
                        $(this).addClass("check_error");
                        //长度不相等即为错
                        $(this).find(".qt_answer").addClass('qt_error')
                    } else {
                        //去除空元素
                        answerNum.forEach(function (value) {
                            if ($.trim(value)) {
                                newAnswer.push(value)
                            }
                        });
                        if (fillNum !== newAnswer.length) {
                            $(this).addClass("check_error");
                            //长度不相等即为错
                            $(this).find(".qt_answer").addClass('qt_error')
                        }
                    }
                }
                if (type == '5') {
                    //简答题答案为空时标记为错误
                    if (answerText.length === 0) {
                        $(this).addClass("check_error");
                        $(this).find(".qt_answer").addClass('qt_error')
                    }
                }
            });
        }

        function changeType(tar, title, dataType, inputType) {
            tar.parent().siblings('.type-name').text(title);
            tar.parents('.qt_title').siblings('.key').find('input').attr('type', dataType);
            tar.parents('.question').attr('data-type', inputType)
        }

        //当题号过长时改变字号
        function changeSize(ii) {
            $(".question .qt_title .title").eq(ii).each(function (index, element) {
                var $numWords = $(this).text().length;
                if ($numWords == 4) {
                    $(this).css({"font-size": "20px"});
                } else if ($numWords == 5) {
                    $(this).css({"font-size": "16px"});
                } else if ($numWords > 5) {
                    $(this).css({"font-size": "14px"});
                }
            });
        }

        function getClassify(value, detail, num) {
            detail.push({
                name: value,
                type: num
            });
        }

        var errorIndex = -1;
        var topNum = 0;
        var bottomNum = 0;
        // 点击显示下一个错误
        $("#nextError").click(function (e) {
            e.stopPropagation();
            e.preventDefault();
            var boxOffsetTop = $('.box').offset().top;
            var error = $("#preview").find(".check_error");
            //先判断滚动条是否到底部
            if (bottomNum === 1) {
                topNum = 0;
                bottomNum = 0;
                errorIndex = -1
            } else {
                errorIndex++;
                if (errorIndex > error.length - 1) {
                    errorIndex = -1;
                }
                topNum += parseInt(error.eq(errorIndex).offset().top - boxOffsetTop - 10);
            }
            $('.box').scrollTop(topNum);
        });

        //滚动检测
        $('.box').scroll(function () {
            if ($(this).scrollTop() + $(this).height() >= $('#preview').height()) {
                errorIndex = -1;
                topNum = 0;
                bottomNum = 1
            }

        });
        //导入试题
        $("#importBtn").click(function (e) {
            e.stopPropagation();
            e.preventDefault();
            var previewHtml = $('#preview').html();
            var previewText = $('#preview').text();

            if ($.trim(previewHtml) === '' || $.trim(previewText) === '') {
                alert('导入内容不能为空！');
                return false
            }

            if ($('.check_error').length > 0) {
                alert('存在错误，请检查试题！');
                return false;
            }
            var text = $("#text-input .fr-view").html();
            $("#errorText , #errorTextNew").hide();
            if ($("input[name=classification]").val() == '') {
                alert("请选择试题分类！");
                return false;
            } else {
                var data = serializeFn();
                var dataForm = JSON.stringify(data);
                var tip = layer.load(0, {shade: false});
                $.ajax({
                    type: "POST",
                    cache: false,
                    headers: {"cache-control": "no-cache"},
                    dataType: "json",
                    contentType: "application/json",
                    url: "{{ url_for('main.importQT') }}",
                    data: dataForm,
                    success: function (msg) {
                        layer.close(tip);
                        var message = "成功导入 " + msg + " 道试题";
                        layer.open({
                            title: '成功',
                            content: message,
                            icon: 1,
                            end: function () {
                                location.href = "{{ url_for('main.question_list')}}";
                            }
                        });

                    }
                });
            }
        });

        // 组织导入试题的信息
        function serializeFn() {
            var classification = $("input[name=classification]").val();
            var data = [];

            $("#preview").find(".question").each(function (index, element) {
                var type = $(this).attr('data-type');
                var reQuestion = $(this).find(".qt_title").html().replace(/^[\s\S]*<span class="type-box"[\s\S]*>[\s\S]+<\/span>([\s\S]*)$/, "$1");
                var question = escapeHTML(reQuestion);
                var answer1 = $(this).find(".key_A").length == 0 ? "" : (escapeHTML($(this).find(".key_A").html()) == "" ? " " : escapeHTML($(this).find(".key_A").html()));
                var answer2 = $(this).find(".key_B").length == 0 ? "" : (escapeHTML($(this).find(".key_B").html()) == "" ? " " : escapeHTML($(this).find(".key_B").html()))
                var answer3 = $(this).find(".key_C").length == 0 ? "" : (escapeHTML($(this).find(".key_C").html()) == "" ? " " : escapeHTML($(this).find(".key_C").html()))
                var answer4 = $(this).find(".key_D").length == 0 ? "" : (escapeHTML($(this).find(".key_D").html()) == "" ? " " : escapeHTML($(this).find(".key_D").html()))
                var answer5 = $(this).find(".key_E").length == 0 ? "" : (escapeHTML($(this).find(".key_E").html()) == "" ? " " : escapeHTML($(this).find(".key_E").html()))
                var answer6 = $(this).find(".key_F").length == 0 ? "" : (escapeHTML($(this).find(".key_F").html()) == "" ? " " : escapeHTML($(this).find(".key_F").html()))
                var answer7 = $(this).find(".key_G").length == 0 ? "" : (escapeHTML($(this).find(".key_G").html()) == "" ? " " : escapeHTML($(this).find(".key_G").html()))
                var answer8 = $(this).find(".key_H").length == 0 ? "" : (escapeHTML($(this).find(".key_H").html()) == "" ? " " : escapeHTML($(this).find(".key_H").html()))
                if (type == "1" || type == "2") {
                    var key = escapeHTML($(this).find(".qt_answer").html()).replace(/&nbsp;/g, "").toUpperCase().replace(/<BR CLASS="MARKDOWN_RETURN">/g, "");
                } else if (type == "3") {
                    var key = escapeHTML($(this).find(".qt_answer").html()).replace(/(^\s+)|(\s+$)/g, "").replace(/(正确|对)/, 1).replace(/(错误|错)/, 0);
                } else {
                    var key = escapeHTML($(this).find(".qt_answer").html());
                }
                var comKeyWord = $(this).find(".qt_comKeyWord").length == 0 ? "" : escapeHTML($(this).find(".qt_comKeyWord").html());
                var coreKeyWord = $(this).find(".qt_coreKeyWord").length == 0 ? "" : escapeHTML($(this).find(".qt_coreKeyWord").html());
                var analysis = $(this).find(".qt_analysis").length == 0 ? "" : escapeHTML($(this).find(".qt_analysis").html());
                var difficult = $(this).find(".qt_difficult").length == 0 ? "" : escapeHTML($(this).find(".qt_difficult").html());
                if ($(this).find(".qt_difficult").length != 0) {
                    difficult = difficult.slice(0, 2);
                }
                var label = $(this).find(".qt_label").length == 0 ? "" : escapeHTML($(this).find(".qt_label").html());
                data[index] = {
                    "classification": classification,
                    "type": type,
                    "difficult": difficult,
                    "question": question,
                    "answer1": answer1,
                    "answer2": answer2,
                    "answer3": answer3,
                    "answer4": answer4,
                    'normal_words': comKeyWord,
                    "key_words": coreKeyWord,
                    "key": key,
                    "analysis": analysis,
                    "label": label,
                    "disorder": 1
                };
                // 若不存在该项则不存入
                for (i in data[index]) {
                    if (data[index][i] == "" || !data[index][i]) {
                        delete data[index][i];
                    }
                }
            });
            return data;
        }

        //转义部分，换行　$markdown_return 进行两次替换
        // 按照URL换码协议，＋会被转换成空格，所以要做相应处理
        function escapeHTML(text) {
            return text.replace(/^[\s\S]*<span class="title"[\s\S]*>[\s\S]+<\/span>([\s\S]*)$/, "$1")
                .replace(/<br class="markdown_return">/g, "$markdown_return")
                .replace(/\&nbsp;/g, " ")
                .replace(/\$markdown_return/g, '<br class="markdown_return">')
        }


    </script>
{% endblock %}